<template>
  <div>
    <BreadCrumbShow />

    <div class="apply-operate">
      <el-button
        :disabled="toApplyNum == 0"
        type="primary"
        size="small"
        @click="toApplyRead"
        >申请{{ listTitle }}({{ toApplyNum }})</el-button
      >
      <el-button
        size="small"
        type="primary"
        @click="clearTempList"
        :disabled="tempBoxList.length == 0"
        >清空临时列表</el-button
      >
      <el-button size="small" @click="batchApplyBorrowing"
        >批量导入{{ listTitle }}</el-button
      >
    </div>

    <ElTable
      refName="tempList"
      @select="selectHandle"
      @pageChange="pageChange"
      @selectionChange="selectionChange"
      :type="2"
      :data-source="tempBoxList"
      :data-config="tableConfig"
      :total="total"
      :pageSize="pageSize"
      :pageNum="pageNum"
      :isLoading="isLoading"
      :defaultAllSelected='true'
      :showPagination="false"
    >
      <template #boxCode="{ scope }">
        <BoxIconShow :rowInfo="scope.row" />
      </template>
      <template #boxTag="{ scope }">
        <div class="cell-tag">
          <span v-for="(tags, index) in scope.row.boxTagList" :key="index">
            <el-tag
              v-if="index <= 5 && tags.tag.length <= 15"
              class="box-tag mr-5"
              type="info"
              size="small"
            >
              {{ tags.tag }}
            </el-tag>
            <el-tooltip
              class="item"
              effect="light"
              :content="tags.tag"
              placement="top"
            >
              <el-tag
                v-if="index <= 5 && tags.tag.length > 15"
                class="box-tag mr-5"
                type="info"
                size="small"
              >
                {{ tags.tag.substring(0, 15) + "..." }}
              </el-tag>
            </el-tooltip>
          </span>
          <el-tag
            type="info"
            size="small"
            class="box-tag box-tag-end"
            @click="goBoxDetail(scope.row)"
            v-if="scope.row.boxTagList && scope.row.boxTagList.length > 6"
            >......</el-tag
          >
        </div>
      </template>
      <template #rackCode="{ scope }">
        <!-- 只有是档案窍存在云窍箱子中 才会有 云窍号-index  去点击查询 -->
        <span @click="showNext(scope.row)" class="hand statusOrange" v-if="scope.row.boxType == 5 && scope.row.userBoxSubBean && scope.row.userBoxSubBean.mainBoxCode">{{scope.row.userBoxSubBean.mainBoxCode }}-{{ scope.row.userBoxSubBean.index}}</span>
        <span v-else>{{scope.row.rackCode && scope.row.rackCode.code}}</span>
      </template>
      <template #operate="{ scope }">
        <el-button type="primary" size="mini" @click="removeTemp(scope.row)"
          >移除</el-button
        >
        <el-button size="mini" @click.native="goBoxDetail(scope.row)" :class="boxCodeList.includes(scope.row.boxCode)?'click-ago': ''"
          >详情</el-button
        >
      </template>

      <template #bottom-btn>
        <el-button
          :disabled="toApplyNum == 0"
          type="primary"
          size="small"
          @click="toApplyRead"
          >申请{{ listTitle }}({{ toApplyNum }})</el-button
        >
      </template>
    </ElTable>

    <!-- 批量导入调阅 -->
    <ImportReadDialog
      ref="ImportReadDialog"
      :title="'批量导入' + listTitle"
      :isImportRead="isImportRead"
      @submitImport="submitImport"
      @modeUpload="modeUpload"
      @closeImportDialog="closeDialog"
    />

    <!--申请调阅 -->
    <ApplyReadDialog
      :isApplyRead="isApplyRead"
      :userInfo="userInfo"
      :selectedList="selectedList"
      @closeApplyDialog="closeDialog"
      @getList="getTempBoxList"
    />

    <!-- 申请回库 -->
    <ApplyBackDialog
      :isApplyBack="isApplyBack"
      :userInfo="userInfo"
      :selectedList="selectedList"
      @closeApplyDialog="closeDialog"
      @getList="getTempBoxList"
    />

    <!-- 申请销毁 -->
    <ApplyDestroyDialog
      :isApplyDestroy="isApplyDestroy"
      :userInfo="userInfo"
      :selectedList="selectedList"
      @closeApplyDialog="closeDialog"
      @getList="getTempBoxList"
    />

    <!-- 展示云窍下的档案窍 -->
    <ShowNextBox
      :isShowNextBox.sync="isShowNextBox"
      @closeDialog="closeDialog"
      :showRow="showRow"
      :userBoxList='tempBoxList'
    />
  </div>
</template>

<script>
import ElTable from "@/components/table/ElTable.vue";
import ImportReadDialog from "./components/ImportReadDialog";
import ApplyReadDialog from "./components/ApplyReadDialog";
import ApplyBackDialog from "../back-warehouse-manage/components/ApplyBackDialog";
import ApplyDestroyDialog from "../destroy-manage/components/ApplyDestroyDialog";
import BoxIconShow from "@/components/public-style/BoxIconShow";
import ShowNextBox from "./components/ShowNextBox.vue";
import {
  getTempBoxList,
  getTaglistByUserBoxId,
  getTaglistByUserBoxIds,
  toRemoveTemp,
  toImportTemp,
} from "../../api/access-manage/index";
import Cookies from "js-cookie";

export default {
  name: "accessTempList",
  data() {
    return {
      boxCodeList: [],
      listTitle: "调阅",
      listType: 0,
      userInfo: {},
      isApplyRead: false,
      isApplyBack: false,
      isApplyDestroy: false,
      isImportRead: false,
      uploadFile: {},
      selectedList: [],
      pageTitle: "临时调阅列表",
      toApplyNum: 0,

      tempBoxList: [],
      tableConfig: [],
      isLoading: false,
      total: 0,
      pageSize: 10,
      pageNum: 1,
      isShowNextBox: false,
      showRow: {}
    };
  },
  components: {
    ElTable,
    ImportReadDialog,
    ApplyReadDialog,
    BoxIconShow,
    ApplyBackDialog,
    ApplyDestroyDialog,
    ShowNextBox
  },
  mounted() {
    this.listType = this.$route.params.type || this.getTypeRelyRoute();
    if (this.listType == 1) {
      this.listTitle = "回库";
    }
    if (this.listType == 2) {
      this.listTitle = "销毁";
    }

    this.tableConfig = [
      {
        label: "类别 | 编号",
        prop: "boxCode",
        width: "300",
      },
      {
        prop: "boxTag",
        label: "标签",
        width: "380",
        showTooltip: false,
      },
      {
        prop: "rackCode",
        label: "货位",
      },
      this.listType == 0 && {
        prop: "createdOn",
        label: "加入时间",
      },
      {
        prop: "operate",
        label: "操作",
        width: "200",
      },
    ].filter((v) => v);
    this.userInfo = JSON.parse(Cookies.get("userInfo"));
    this.getTempBoxList();

    this.boxCodeList = []
  },
  methods: {
    // 点击档案窍的云窍窍号，展示它下级所有的档案窍
    showNext(row) {
      this.showRow = row
      // 打开弹窗展示
      this.isShowNextBox = true
    },
    // 根据路由判断listType
    getTypeRelyRoute() {
      const name = this.$route.name;
      if (name == "AccessTempList") {
        return 0;
      }
      if (name == "BackTempList") {
        return 1;
      }
      if (name == "DestroyTempList") {
        return 2;
      }
    },
    // 分页变化
    pageChange(emitData) {
      this.pageNum = emitData.pageNum;
      this.pageSize = emitData.pageSize;
      this.getTempBoxList();
    },
    // 选择项变化
    selectionChange(selectArr) {
      this.toApplyNum = selectArr.length;
      this.selectedList = selectArr;
    },
    // 点击多选框 选中
    selectHandle(a) {},
    // 获得临时列表
    getTempBoxList() {
      this.isLoading = true;
      const params = {
        // pageSize: this.pageSize,
        // pageNum: this.pageNum,
      };
      new Promise((resolve) => {
        //  0调阅 1回库 2销毁 3永久下架
        getTempBoxList(this.listType, params)
          .then((res) => {
            res.data.map((e) => {
              e.createdOn = this.$moment(e.createdOn * 1000).format(
                "YYYY-MM-DD HH:mm:ss"
              );
            });

            this.tempBoxList = res.data;
            this.total = res.total;

            // this.tempBoxList.map((item) => {
            //   getTaglistByUserBoxId({ userBoxId: item.id }).then((tagRes) => {
            //     item["boxTagList"] = tagRes.data;
            //     this.$forceUpdate();
            //   });
            // });

            if (this.tempBoxList.length > 0) {
              let ids = [];
              this.tempBoxList.map((item) => {
                ids.push(item.userBoxId);
              });

              getTaglistByUserBoxIds(ids).then((res) => {
                this.tempBoxList.map((item) => {
                  res.data.map((tags) => {
                    if (tags.userBoxId == item.userBoxId) {
                      item["boxTagList"] = tags.tagList.filter(m => m.tag != ';' && m.tag != '；');
                      this.$forceUpdate();
                    }
                  });
                });
              });
            }

            this.isLoading = false;
          })
          .catch((err) => {
            this.isLoading = false;
          });
        resolve();
      });
    },
    // 批量导入调阅 - 显示弹框
    batchApplyBorrowing() {
      this.isImportRead = true;
    },
    // 上传文件
    modeUpload(param) {
      this.uploadFile = param;
    },
    // 批量导入调阅 - 提交
    submitImport() {
      if (!this.uploadFile.file) {
        this.$message({
          type: "error",
          message: "请选择文件后上传",
        });
        return;
      }
      let formData = new FormData();
      formData.append("file", this.uploadFile.file);
      // this.$refs.uploadButton.submit();
      // this.$refs.uploadButton.clearFiles();
      toImportTemp(formData, { type: this.listType })
        .then((res) => {

          if (res.code == 200) {
            this.commonFun.getTempReturnInfo(res.data, this)
            this.isImportRead = false;
            this.getTempBoxList();
          }
        })
        .catch((err) => {
          this.isLoading = false;
        });
    },
    // 展示 申请调阅 弹窗
    toApplyRead() {
      if (this.listType == 0) {
        this.isApplyRead = true;
      }
      if (this.listType == 1) {
        this.isApplyBack = true;
      }
      if (this.listType == 2) {
        this.isApplyDestroy = true;
      }
    },
    // 关闭申请调阅弹框
    closeDialog() {
      this.isApplyRead = false;
      this.isApplyBack = false;
      this.isApplyDestroy = false;
      this.isImportRead = false;
      this.isShowNextBox = false
    },
    // 移除单个
    removeTemp(row) {
      this.$confirm("确定移除该窍吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          toRemoveTemp({ type: this.listType }, [row.userBoxId]).then((res) => {
            this.$message({
              type: "success",
              message: "移除成功",
            });

            this.getTempBoxList();
          });
        })
        .catch((err) => {});
    },
    // 清空临时列表
    clearTempList() {
      this.$confirm("确定清空临时列表吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // userBoxId不传 删除所有
        toRemoveTemp({ type: this.listType }).then((res) => {
          this.$message({
            type: "success",
            message: "临时列表已清空",
          });

          this.getTempBoxList();
        });
      });
    },
    // 去 窍详情
    goBoxDetail(row) {
      this.boxCodeList.push(row.boxCode)
      // this.$router.push({
      //   name: "BoxDetail",
      //   params: {
      //     id: row.userBoxId,
      //   },
      // });
      let routeUrl = this.$router.resolve({
        name: "BoxDetail",
        params: { id: row.userBoxId },
      });
      window.open(routeUrl.href, "_blank");
    },
  },
};
</script>

<style lang="scss" scoped>
.apply-operate {
  margin-bottom: 30px;
  margin-top: 10px;
}
.operate {
  .el-button--text {
    color: #666 !important;
    &:hover {
      color: coral !important;
    }
  }
}

.box-code {
  display: flex;
  align-items: center;
  .el-image-box {
    height: 60px;
    width: 80px;
    margin-right: 10px;
    text-align: center;
    .el-image {
      height: 100%;
    }
  }
  .title {
    font-size: 12px;
    font-weight: 550;
    color: #333;
  }
}

// 列表中的tag
.cell-tag {
  .box-tag {
    margin-bottom: 5px;
    // cursor: pointer;
  }
  .box-tag-end {
    cursor: pointer;
  }
}

.click-ago {
  background: rgba(255, 139, 49, 0.2);
}
</style>
